package com.cats.template.sys.config.authority;

import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.cats.template.sys.aggservices.SysAggService;
import com.cats.template.sys.pojo.dto.PermissionDto;
import com.cats.template.sys.pojo.dto.RoleDto;
import com.cats.template.sys.pojo.dto.UserDto;
import com.cats.template.sys.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.Objects;
import java.util.Set;

/**
 * @author duxiaobo
 * @date 2021/9/811:29 上午
 */
@Slf4j
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private SysAggService sysAggService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("进入鉴权");
        // 获取用户名
        UserDto user = (UserDto) principalCollection.getPrimaryPrincipal();
        if (Objects.isNull(user)) {
            return null;
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 根据用户名获取用户登录信息

        // 设置用户角色
        Set<RoleDto> roles = sysAggService.getRolesByUserId(user.getId());
        if (!CollectionUtils.isEmpty(roles)) {
            roles.forEach(role -> authorizationInfo.addRole(role.getRoleCode()));
        }
        // 设置权限
        Set<PermissionDto> permissions = sysAggService.getPermissionDtoSetByUserId(user.getId());
        if (!CollectionUtils.isEmpty(permissions)) {
            permissions.forEach(permission -> authorizationInfo.addStringPermission(permission.getPerms()));
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        log.info("进入验证token");
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = JwtUtils.getUsername(token);
        if (StringUtils.isEmpty(username)) {
            throw new AuthenticationException("token错误!");
        }
        UserDto user = sysAggService.getUserAndRolesByUserName(username);
        if (Objects.isNull(user)) {
            throw new UnknownAccountException("用户不存在!");
        }
        if (user.getIsLock()) {
            throw new LockedAccountException("用户被锁定");
        }
        try {
            if (JwtUtils.verify(token)) {
                return new SimpleAuthenticationInfo(user, token, getName());
            } else {
                throw new AuthenticationException("token认证失败!");
            }
        } catch (TokenExpiredException e) {
            throw new AuthenticationException("token已过期!");
        } catch (SignatureVerificationException e) {
            throw new AuthenticationException("用户名或密码不正确!");
        }
    }

    /**
     * 清除登陆用户授权信息缓存.
     */
    public void clearCached() {
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }


}
